﻿using Iworld.Client.Framework;
using Iworld.Client.Framework.AuthorService;
using Iworld.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Iworld.Client
{
    public partial class MainPage : UserControl, IMainPage<Page,Pop>
    {

     AuthorServiceClient client = new AuthorServiceClient();
        bool settingOut = false;
        bool isDoing = false;
        public MainPage()
        {
            InitializeComponent();
            client.KeepHeartbeatCompleted += KeepHeartbeatCompleted;
            Storyboard sb = new Storyboard();
            sb.Duration = new Duration(new TimeSpan(0, 0, 5));
            sb.Completed += sb_Completed; 
            sb.Begin(); 
        }


        void sb_Completed(object s, EventArgs a)
        { 
            if (!isDoing && !settingOut && DataManager.HaveValue<string>(DataKey.Iworld_Token))
            {
                client.KeepHeartbeatAsync(new KeepHeartbeatImport() { Token = DataManager.GetValue<string>(DataKey.Iworld_Token) });
                isDoing = true;
            }
            Storyboard ssb = (Storyboard)s;
            ssb.Begin();
        }



        void KeepHeartbeatCompleted(object sender, KeepHeartbeatCompletedEventArgs e)
        {
            try
            {
                isDoing = false;
                if (e.Result.Success)
                {
                    DataManager.SetValue(DataKey.User_SelfInfo, e.Result.Info.SelfInfo);
                    DataManager.SetValue(DataKey.SettingOfGame, e.Result.Info.SettingOfGame);
                }
                else
                {
                    settingOut = true;
                    ChildWindow cw = new ChildWindow();
                    cw.Content = new TextBlock() { Text = e.Result.Error , TextWrapping= TextWrapping.Wrap};
                    cw.Closed += Logout;
                    cw.Show();
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }

        void Logout(object sender, EventArgs e)
        {
            ClientViewModelService.Current.JumpToDefaultPage();
            this.settingOut = false;
        }

        /// <summary>
        /// 显示目标子界面
        /// </summary>
        /// <param name="userControl">所要显示的子界面</param>
        public void Show(UIElement userControl)
        {
            body.Children.Clear();
            body.Children.Add(userControl);
        }

        /// <summary>
        /// 关闭主窗口
        /// </summary>
        public void CloseMainWindow()
        {
            if (App.Current.IsRunningOutOfBrowser)
            {
              App.Current.MainWindow.Close();
            }
        }

        /// <summary>
        /// 注册可跳转界面
        /// </summary>
        public void RegisterViews(ViewModelServiceBase<Page,Pop> service)
        {
            //获取目标程序集
            Assembly assembly = Assembly.GetExecutingAssembly();

            #region 注册可跳转界面

            assembly.GetTypes()
                .Where(x => x.GetCustomAttributes(true).Any(t => t is Iworld.ViewModel.ViewAttribute))
                .ToList().ForEach(x =>
                {
                    var attribute = x.GetCustomAttributes(true).First(t => t is Iworld.ViewModel.ViewAttribute)
                        as Iworld.ViewModel.ViewAttribute;
                    service.RegisterPage((Page)attribute.Page
                        , x.Name
                        , attribute.IsDefault
                        , new UIElementCreater(() =>
                        {
                            return assembly.CreateInstance(x.FullName) as UIElement;
                        }));
                });

            #endregion

            #region 注册弹窗

            assembly.GetTypes()
                .Where(x => (x.GetInterfaces().Any(t => t == typeof(IPop)))
                    && (x.GetCustomAttributes(true).Any(t => t is PopAttribute)))
                .ToList().ForEach(_type =>
                {
                    PopAttribute attribute = _type.GetCustomAttributes(true)
                        .First(x => x is PopAttribute) as PopAttribute;
                    service.RegisterPop((Pop)attribute.Pop
                        , new PopCreater(() =>
                        {
                            return assembly.CreateInstance(_type.FullName) as IPop;
                        }));
                });

            #endregion
        }

        private void DragMove(object sender, MouseButtonEventArgs e)
        {
            if (App.Current.IsRunningOutOfBrowser)
            {
                App.Current.MainWindow.DragMove();
            }
        }

        private void CloseSmallWindow(object sender, RoutedEventArgs e)
        {
           /* if (win_UnreadNotices.Visibility == System.Windows.Visibility.Collapsed) { return; }
            win_UnreadNotices.Visibility = System.Windows.Visibility.Collapsed;
            ShowSmallWindow();*/
        }



    }
}
